package com.longqin.wechat.config;

import java.io.IOException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import com.longqin.wechat.entity.MyException;
import com.longqin.wechat.util.ResponseEnum;

/**
 * 用户对外部接口的http请求
 */
@Configuration
public class RestTemplateConfig {
	
	/**获取RestTemplate
	 * @return
	 */
	@Bean(name="restTemplate")
	protected RestTemplate onRestTemplate() {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setReadTimeout(30000);
		factory.setConnectTimeout(30000);//连接超时时间
		RestTemplate restTemplate = new RestTemplate(factory);
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			
			//异常处理重写方法(主要捕捉403等无权限访问异常)
			@Override
			protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
				byte[] body = getResponseBody(response);
				throw new MyException(ResponseEnum.ERROR.getCode(),"请求远程接口失败:"+new String(body,"utf-8"));
			}
		});
		return restTemplate;
	}
}
 